<template>
  <div class="container">
    <!-- 卡片 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ newOrEditor ? "试题录入" : "试题修改" }}</span>
      </div>
      <!-- 录入表单 -->
      <el-form
        class="inputTestQuestion"
        :model="itqForm"
        :rules="itqRules"
        ref="itqFormRef"
        label-width="100px"
        label-position="left"
      >
        <div class="width_box">
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID" width="470px">
            <el-select
              v-model="itqForm.subjectID"
              placeholder="请选择学科"
              @change="selectSubject($event)"
            >
              <el-option
                v-for="(item, index) in subjectsList"
                :key="index"
                :label="item.subjectName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录:" prop="catalogID">
            <el-select v-model="itqForm.catalogID" placeholder="请选择目录">
              <el-option
                v-for="(item, index) in directorysList"
                :key="index"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select v-model="itqForm.enterpriseID" placeholder="请选择企业">
              <el-option
                v-for="(item, index) in componysList"
                :key="index"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 双select联动选择 -->
          <el-row>
            <el-col
              ><el-form-item label="城市:" prop="province">
                <!-- 第一个select -->
                <el-select
                  v-model="itqForm.province"
                  @change="selectCity($event)"
                  clearable
                  placeholder="请选择城市"
                  filterable
                  class="city-select"
                  @clear="itqForm.city = ''"
                >
                  <el-option
                    v-for="(item, index) in cityList"
                    :label="item"
                    :key="index"
                    :value="item"
                  ></el-option>
                </el-select> </el-form-item
            ></el-col>

            <!-- 第二个select -->
            <el-col
              ><el-form-item prop="city">
                <el-select
                  v-model="itqForm.city"
                  clearable
                  class="city-select"
                  placeholder="请选择区县"
                  filterable
                >
                  <el-option
                    v-for="(item, index) in countryList"
                    :label="item"
                    :key="index"
                    :value="item"
                  ></el-option>
                </el-select> </el-form-item
            ></el-col>
          </el-row>

          <!-- 方向 -->
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="itqForm.direction" placeholder="请选择方向">
              <el-option
                v-for="(item, index) in directions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 选择题目类型(单选，多选，简答) -->
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group
              v-model="itqForm.questionType"
              @change="changeDifficulty"
            >
              <el-radio :label="'1'">单选</el-radio>
              <el-radio :label="'2'">多选</el-radio>
              <el-radio :label="'3'">简答</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 难度选择 -->
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="itqForm.difficulty">
              <el-radio :label="'1'">简单</el-radio>
              <el-radio :label="'2'">一般</el-radio>
              <el-radio :label="'3'">困难</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 题干 -->
        <el-form-item label="题干:" prop="question">
          <quill-editor
            v-model="itqForm.question"
            ref="myQuillEditor"
            :options="editorOption"
          >
          </quill-editor>
        </el-form-item>

        <!-- 单选选项区域 -->
        <el-form-item
          v-if="itqForm.questionType == '1'"
          label="选项:"
          prop="question_item"
        >
          <el-radio-group v-model="rightAnswer">
            <el-row
              class="item_row"
              v-for="(item, index) in itqForm.options"
              :key="index"
            >
              <el-col :span="14">
                <el-radio :label="item.code">
                  <span> {{ item.code }}: </span>
                  <el-input
                    placeholder=""
                    v-model="item.title"
                  ></el-input> </el-radio
              ></el-col>
              <!-- 上传图片部分 -->
              <el-col :span="10">
                <el-upload
                  class="avatar-uploader"
                  action="http://127.0.0.1:1024"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                >
                  <img
                    v-if="itqForm.options.img"
                    :src="itqForm.options.img"
                    class="avatar"
                  />
                  <div v-else class="avatar-uploader-icon">
                    上传图片

                    <i class="deletePic el-icon-close"></i>
                  </div> </el-upload
              ></el-col>
              <!-- ================== --></el-row
            >
          </el-radio-group>
        </el-form-item>

        <!-- 多选选项区域 -->
        <el-form-item
          v-if="itqForm.questionType == '2'"
          label="选项:"
          prop="question_item"
        >
          <el-checkbox-group v-model="rightAnswers">
            <el-row
              class="item_row"
              v-for="(item, index) in itqForm.options"
              :key="index"
            >
              <el-col :span="14">
                <el-checkbox :label="item.code">
                  <span> {{ item.code }}: </span>
                  <el-input
                    placeholder=""
                    v-model="item.title"
                  ></el-input> </el-checkbox
              ></el-col>
              <!-- 上传图片部分 -->
              <el-col :span="10">
                <el-upload
                  class="avatar-uploader"
                  action="http://127.0.0.1:1024"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                >
                  <img
                    v-if="itqForm.options.img"
                    :src="itqForm.options.img"
                    class="avatar"
                  />
                  <div v-else class="avatar-uploader-icon">
                    上传图片
                    <i class="deletePic el-icon-close"></i>
                  </div>
                </el-upload>
              </el-col>
            </el-row>
          </el-checkbox-group>
        </el-form-item>

        <!-- 添加项 -->
        <el-form-item>
          <el-button @click="addOption" type="danger" class="el-icon-plus"
            >添加选项和答案</el-button
          ></el-form-item
        >
        <!-- 解析视频 -->
        <el-form-item label="视频解析:">
          <el-input
            class="videoUrl"
            v-model="itqForm.videoURL"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>

        <!-- 答案解析 -->
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor
            v-model="itqForm.answer"
            ref="answerAnalyseEditor"
            :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注:" prop="remarks">
          <el-input
            class="remarksInput"
            type="textarea"
            :rows="2"
            v-model="itqForm.remarks"
          >
          </el-input>
        </el-form-item>

        <!-- 试题标签部分 -->
        <el-form-item label="试题标签:" prop="tags">
          <el-select
            class="tagChoose"
            v-model="itqForm.tags"
            placeholder="请选择试题标签"
          >
            <el-option
              v-for="(item, index) in tagsList"
              :key="index"
              :label="item.tagName"
              :value="item.tagName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button v-if="newOrEditor" type="primary" @click="allotQuestion"
            >确认提交</el-button
          >
          <el-button v-else type="danger" @click="allotEditQuestion"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addQuillTitle } from '@/utils/title'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants' // 方向
import { list as sList } from '@/api/hmmm/subjects' // 学科
import { list } from '@/api/hmmm/directorys' // 目录
import { list as cList } from '@/api/hmmm/companys' // 企业
import { list as tList } from '@/api/hmmm/tags' // 标签
import { add, detail, update } from '@/api/hmmm/questions' // 添加题库api
import { mapState } from 'vuex'
import { mapMutations } from 'vuex'
export default {
  name: 'new',
  data() {
    return {
      editorOption: {
        placeholder: '请在这里输入...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link'] // 代码块,上传图片,链接
          ]
        }
      }, // 富文本编辑器配置项
      subjectsList: [],
      directorysList: [],
      componysList: [],
      tagsList: [],
      itqForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        videoURL: '',
        answer: '',
        remarks: '',
        tags: '',
        // 题型数据
        questionType: '1',
        // 难度数据
        difficulty: '1',
        // 题干数据
        question: '',
        // 选项数据
        options: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ]
      },
      // 表单校验
      itqRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择试题类型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      },
      // select
      cityList: [],
      countryList: [],
      // 方向数据
      directions: direction,

      // 题干数据
      questionContent: '',
      rightAnswer: '',
      rightAnswers: []
    }
  },
  watch: {
    rightAnswer(val) {
      console.log(val)
      this.itqForm.options.forEach(item => {
        item.isRight = false
        if (item.code == val) {
          item.isRight = true
        }
      })
    },
    rightAnswers(val) {
      console.log(val)
      this.itqForm.options.forEach(item => {
        item.isRight = false
        var flag = val.find(item2 => {
          return item.code == item2
        })
        if (flag) {
          item.isRight = true
        }
      })
    }
  },
  computed: {
    ...mapState(['newOrEditor', 'editData'])
  },
  created() {
   this.getChioceInfo()
  },
  mounted() {
    addQuillTitle()
    this.cityList = provinces() // 获取 城市列表
    this.getTagsList()
    this.getSubjects()
    this.getComponyList()
    this.editQue() // 通过查询vuex中的newOrEditor变量来判断当前是修改模式下还是录入模式
  },
  methods: {
    ...mapMutations(['editFlag']),
    // 确认修改
    async getChioceInfo() {
      const questionId = this.$route.query.id
      if (questionId) {
        try {
          const { data } = await detail({ id: questionId })
          this.itqForm.subjectID = data.subjectName

          this.itqForm.catalogID = data.directoryName
          this.itqForm.province = data.province

          this.itqForm.city = data.city
          this.itqForm.enterpriseID = data.enterpriseID
          this.itqForm.direction = data.direction
          this.itqForm.questionType = data.questionType
          this.itqForm.difficulty = data.difficulty
          this.itqForm.answer = data.answer
          this.itqForm.question = data.question
          this.itqForm.remarks = data.remarks
          this.itqForm.videoURL = data.videoURL
          this.itqForm.tags = data.tags
        } catch (error) {
          this.$message.error('精选试题详情获取失败')
        }
      }
    },
    async allotEditQuestion() {
      const { data: res } = await update(this.itqForm)
      console.log(res)
      if (res.success == true) {
        this.$message.success('修改成功')
        this.itqForm = {
          // subjectID: "",
          // catalogID: "",
          // enterpriseID: "",
          // province: "",
          // city: "",
          // direction: "",
          // videoURL: "",
          // answer: "",
          // remarks: "",
          // tags: "",
          // // 题型数据
          // questionType: "1",
          // // 难度数据
          // difficulty: "1",
          // // 题干数据
          // question: "",
          // // 选项数据
          // options: [
          //   { code: "A", title: "", img: "", isRight: false },
          //   { code: "B", title: "", img: "", isRight: false },
          //   { code: "C", title: "", img: "", isRight: false }
          // ]
        }
        this.editFlag({ flag: true })
        this.$router.push('/questions/list')
      }
    },
    async editQue() {
      if (this.newOrEditor) {
      } else {
        console.log(1)
        console.log(this.editData)
        const { data: res } = await detail(this.editData)
        console.log(res)
        this.itqForm.subjectID = this.editData.subjectID
        this.selectSubject()
        this.itqForm.catalogID = this.editData.catalogID
        this.itqForm.province = res.province
        this.selectCity()
        this.itqForm.city = res.city
        this.itqForm.enterpriseID = this.editData.enterpriseID
        this.itqForm.direction = this.editData.direction
        this.itqForm.questionType = this.editData.questionType
        this.itqForm.difficulty = this.editData.difficulty
        this.itqForm.answer = this.editData.answer
        this.itqForm.question = this.editData.question
        this.itqForm.remarks = this.editData.remarks
        this.itqForm.videoURL = this.editData.videoURL
        this.itqForm.tags = this.editData.tags
        this.itqForm.options = res.options
        this.itqForm.id = res.id
        if (this.editData.questionType == '1') {
          res.options.forEach(item => {
            if (item.isRight) {
              this.rightAnswer = item.code
            }
          })
        } else if (this.editData.questionType == '2') {
          res.options.forEach(item => {
            if (item.isRight) {
              this.rightAnswers.push(item.code)
            }
          })
        }
      }
    },
    // 提交确认表单
    allotQuestion() {
      this.$refs.itqFormRef.validate(async vali => {
        console.log(vali)
        if (vali) {
          try {
            const res = await add(this.itqForm)
            console.log(res)
            this.$message.success('添加成功')
            this.$refs.itqFormRef.resetFields()
            this.itqForm.subjectID = ''
            this.directorysList = []
            this.itqForm.catalogID = ''
            this.itqForm.enterpriseID = ''
            this.itqForm.province = ''
            this.itqForm.answer = ''
            this.itqForm.question = ''
            this.itqForm.difficulty = '1'
            this.itqForm.videoURL = ''
            this.itqForm.options = [
              { code: 'A', title: '', img: '', isRight: false },
              { code: 'B', title: '', img: '', isRight: false },
              { code: 'C', title: '', img: '', isRight: false }
            ]
            this.$router.push('/questions/list')
          } catch (error) {
            console.log(error)
            this.$message.error('添加失败')
          }
        } else {
          return this.$message.error('请将表单补充完整')
        }
      })
    },
    // 获取标签列表
    async getTagsList() {
      const res = await tList({ pagesize: 20 })
      console.log(res)
      this.tagsList = res.data.items
    },
    // 获取城市列表
    async getComponyList() {
      const res = await cList({ pagesize: 100 })
      console.log(res)
      this.componysList = res.data.items
    },
    // 选中学科时触发，获取对应目录
    async selectSubject(e) {
      this.itqForm.catalogID = ''
      const res = await list({ subjectID: e })
      console.log(res)
      this.directorysList = res.data.items
    },
    // 获取学科列表
    async getSubjects() {
      const res = await sList({ pagesize: 100 })
      console.log(res)
      this.subjectsList = res.data.items
    },
    // 题目类型改变时
    changeDifficulty(e) {
      console.log(e)
      this.rightAnswer = ''
      this.rightAnswers = []
    },
    // 上传图片到服务器成功后
    handleAvatarSuccess(file) {
      console.log(file)
    },
    // 增加答案选项
    addOption() {
      var num = this.itqForm.options[this.itqForm.options.length - 1]
      var ascnum = num.code.charCodeAt() // 把字符转换为ascll 67
      console.log(num)
      if (ascnum <= 90) {
        ascnum++
        var newascnum = String.fromCodePoint(ascnum)
        const obj = { code: newascnum, title: '', img: '', isRight: false }
        this.itqForm.options.push(obj)
      }
    },
    // 第一个selet选中时
    selectCity(e) {
      this.countryList = citys(e)
      this.itqForm.city = ''
    }
  }
}
</script>

<style lang="scss">
.box-card {
  margin: 20px !important;
  .width_box {
    width: 600px;
    .el-input--medium .el-input__inner {
      width: 450px;
    }
  }
  .ql-editor p {
    height: 200px;
  }
  .answerItem {
    .el-col-24 {
      margin-bottom: 20px;
    }
  }
  .item_row {
    width: 550px !important;
    display: flex;
    align-items: center !important;
    margin-bottom: 10px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: inline-block;
    cursor: pointer;

    // overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    position: relative;
    width: 100px;
    font-size: 12px;
    color: #8c939d;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
  .deletePic {
    display: block;
    position: absolute;
    right: -5px;
    top: -5px;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    border: 1px solid #ccc;
  }
  .videoUrl {
    width: 300px;
  }
  .remarksInput {
    .el-textarea__inner {
      height: 70px !important;
    }
    width: 300px;
  }
  .tagChoose {
    width: 300px;
  }
}
</style>
